﻿using Microsoft.IdentityModel.Tokens;
using NewCodeAPI.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace NewCodeAPI;

public class JwtHelper
{
    private readonly IConfiguration _configuration;

    public JwtHelper(IConfiguration configuration)
    {
        _configuration = configuration;

    }

    public string CreateToken()
    {
        // 1. 定义需要使用到的Claims
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, "u_admin"), //HttpContext.User.Identity.Name
            new Claim(ClaimTypes.Role, "r_admin"), //HttpContext.User.IsInRole("r_admin")
            new Claim(JwtRegisteredClaimNames.Jti, "admin"),
            new Claim("Username", "Admin"),
            new Claim("Name", "超级管理员")
        };

        // 2. 从 appsettings.json 中读取SecretKey
        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));

        // 3. 选择加密算法
        var algorithm = SecurityAlgorithms.HmacSha256;

        // 4. 生成Credentials
        var signingCredentials = new SigningCredentials(secretKey, algorithm);

        // 5. 根据以上，生成token
        var jwtSecurityToken = new JwtSecurityToken(
            _configuration["Jwt:Issuer"],     //Issuer
            _configuration["Jwt:Audience"],   //Audience
            claims,                          //Claims,
            DateTime.Now,                    //notBefore
            DateTime.Now.AddSeconds(30),    //expires
            signingCredentials               //Credentials
        );

        // 6. 将token变为string
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        return token;
    }

    public static string IssueJwt(SmPerson user)
    {
        // 配置JWT的iss和aud，即发放方和接收方
        string iss = "wdh";
        string aud = "vue";
        // 密钥，用于签名JWT
        string secret = "JD8SD0ASDjsd23j342n547df78swdh";
        // 创建JWT的payload
        var claims = new List<Claim>
            { 
                // 签发时间
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                // JWT的唯一标识
                new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()),
                // 生效时间
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                // 过期时间
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddSeconds(1200)).ToUnixTimeSeconds()}"),
                // 发放方
                new Claim(JwtRegisteredClaimNames.Iss, iss),
                // 接收方
                new Claim(JwtRegisteredClaimNames.Aud, aud)
            };

        // 添加角色信息到payload
        Claim r1 = new Claim(ClaimTypes.Role, user.Role == "0" ? "Admin" : "User");
        claims.Add(r1);

        // 用密钥对JWT进行签名
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        // 创建JWT
        var jwt = new JwtSecurityToken(issuer: iss, claims: claims, signingCredentials: creds);

        // 将JWT转换为字符串格式
        var jwtHandler = new JwtSecurityTokenHandler();
        var encodeJwt = jwtHandler.WriteToken(jwt);

        // 返回JWT字符串
        return encodeJwt;
    }

    public static SmPerson DeserializeJwt(string jwtStr)
    {
        // 创建JWT解析器
        var jwtHandler = new JwtSecurityTokenHandler();
        var context = new NdlsDBContext();
        SmPerson smPerson = new SmPerson();

        // 判断JWT字符串是否为空，并且是否能够被解析
        if (!string.IsNullOrEmpty(jwtStr) && jwtHandler.CanReadToken(jwtStr))
        {
            // 解析JWT
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            smPerson = context.SmPerson.FirstOrDefault(u => u.Id == Convert.ToInt64(jwtToken.Id));
        }
        return smPerson;
    }
}
